package definite.Guide.Book.LayoutManager;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class BoxLayOutDemo implements ItemListener {

	private static int NUM_COMPONENTS = 3;
	private static float xAlignment[] = { Component.LEFT_ALIGNMENT,
		Component.CENTER_ALIGNMENT, Component.RIGHT_ALIGNMENT };

	private static float[] hue = { 0.0f, 0.33f, 0.67f };
	private static BLDComponent[] bldComponent =
		new BLDComponent[NUM_COMPONENTS];
	private boolean sizeIsRandom = false;
	private static boolean restrictSize = true;

	public void populateContentPane(Container contentPane) {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

		// create the rectangle
		int shortSideSize = 15;
		for (int i = 0; i < NUM_COMPONENTS; i++) {
			if (sizeIsRandom) {
				shortSideSize = (int) (30.0 * Math.random()) + 30;
			} else {
				shortSideSize += 10;
			}
			bldComponent[i] =
				new BLDComponent(xAlignment[i], hue[i], shortSideSize,
						restrictSize, sizeIsRandom, String.valueOf(i));
			panel.add(bldComponent[i]);
		}

		// Create the instructions.
		JLabel label =
			new JLabel("Click a rectangle to " + "change its X alignment.");
		JCheckBox cb = new JCheckBox("Restrict maximum rectangle size.");
		cb.setSelected(restrictSize);
		cb.addItemListener(this);

		panel.setBorder(BorderFactory.createLineBorder(Color.red));

		Box box = Box.createVerticalBox();
		box.add(label);
		box.add(cb);

		contentPane.add(panel, BorderLayout.CENTER);
		contentPane.add(box, BorderLayout.PAGE_END);

	}

	static public void notifyBLDComponents() {
		for (int i = 0; i < NUM_COMPONENTS; i++) {
			bldComponent[i].setSizeRestriction(restrictSize);
		}
		bldComponent[0].revalidate();
	}

	public static void main(String[] args) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				JFrame.setDefaultLookAndFeelDecorated(true);
				JFrame frame = new JFrame("BoxLayOut Demo");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

				BoxLayOutDemo demo = new BoxLayOutDemo();
				demo.populateContentPane(frame.getContentPane());

				frame.setLocationRelativeTo(null);
				frame.pack();
				frame.setVisible(true);
			}
		};

		EventQueue.invokeLater(r);
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if (e.getStateChange() == ItemEvent.SELECTED) {
			restrictSize = true;
		} else {
			restrictSize = false;
		}
		notifyBLDComponents();
	}

}
